import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  Dimensions
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import styles from './style';
import px2dp from '../../utils/px2dp';
import {getPaperDetail, beginAswPaper, aswQuestion, aswQuestionList} from '../../service/common';
import BaseUrl from '../../config/BaseUrl';
import {Toast} from '@ant-design/react-native';


// 支持多个标注
let newStart = [];
let newEnd = [];

let aswQuestions = []; // 每道题的答题
// let aqId = ''; // 题目id
let rightCount = 0; // 答对的题目数

const LabelDetail = (props) => {
  const {
    route: {
      params: {epId},
    },
  } = props;
  const widthDe = Dimensions.get('window').width;
  const heightDe = Dimensions.get('window').height;
  const navigation = useNavigation();
  const [data, setData] = useState({});
  let [imgSrc, setImgSrc] = useState("");  // 图片地址
  let [scale, setScale] = useState(1);  // 图片缩放比例
  let [imgHeight, setImgHeight] = useState(1);  // 图片原始高度
  const [fullScreen, setFullScreen] = useState(0);
  const [apId, setApId] = useState("");
  const [aqId, setAqId] = useState("");
  let [paperTotal, setPaperTotal] = useState(0);  // 试卷题目总数
  let [paperTh, setPaperTh] = useState(1);  // 试卷当前第几道题
  const [answer, setAnswer] = useState();
  const [startP, setStartP] = useState({pageX:0, pageY:0});
  const [endP, setEndP] = useState({pageX:0, pageY:0});
  // 支持多个标注
  const [newStartP, setNewStartP] = useState([]);
  const [newEndP, setNewEndP] = useState([]);

  useEffect(() => {
    navigation.setOptions({
      title: '标注训练',
    });
    getPaperDetailQuest();

    navigation.addListener('focus', () => {
      aswQuestions = []; // 每道题的答题
      // aqId = ''; // 题目id
      rightCount = 0; // 答对的题目数
      // 开始答题
      beginAswPaper({epId}).then((res)=>{
        console.log(res);
        setApId(res.data.apId);
        questionList(res.data.apId, 1);
      });
    });
    
  }, [navigation]);

  // 获取题目
  const questionList = (apId, pn) => {
    newStart = [];
    newEnd = [];
    setNewStartP([]);
    setNewEndP([]);
    aswQuestionList({ apId, pn, ps:1 }).then((res)=>{
      console.log(res);
      const list = res.rows;
      setAqId(list[0].aqId);
      setPaperTotal(res.total);
      setPaperTh(list[0].eqOrder);
      // 获取图片缩放比例
      let img = BaseUrl.imgurl + list[0].eqImage;
      setImgSrc(img);
      Image.getSize(img, (width, height) => {
        setScale(widthDe / width);
        setImgHeight(height);
      })
    });
  }

  const getPaperDetailQuest = () => {
    getPaperDetail({epId}).then((res) => {
      // console.log(res);
      setData(res.data);
    });
  };

  // 手势操作，提交标注
  const setAswQuestion = () => {
    aswQuestion({
      apId,
      aqId,
      "aswQstOptions": [{
          "aqoLux": startP.pageX,
          "aqoLuy": startP.pageY,
          "aqoRdx": endP.pageX,
          "aqoRdy": endP.pageY
      }]
      // "aswQstOptions" : ()=>{
      //   let aqo = [];
      //   for (let index = 0; index < newEndP.length; index++) {
      //     // const element = array[index];
      //     aqo.push({
      //       "aqoLux": newStartP[index].pageX,
      //       "aqoLuy": newStartP[index].pageY,
      //       "aqoRdx": newEndP[index].pageX,
      //       "aqoRdy": newEndP[index].pageY
      //     })
      //   }
      //   return aqo;
      // }
    }).then((res) => {
      console.log(res);
      if (res.data.aqIsTrue === 'Y'){
        // console.log('Yes');
        rightCount++;
      }
      setAnswer(res.data);
    });
  };

  const onPressIn = (evt)=> {
    // console.log(evt.nativeEvent, 'start-----');
    setStartP(evt.nativeEvent);
    newStart.push(evt.nativeEvent);
    setNewStartP(newStart);
  };
  const onPressOut = (evt)=> {
    // console.log(evt.nativeEvent, 'end-----');
    setEndP(evt.nativeEvent);
    newEnd.push(evt.nativeEvent)
    setNewEndP(newEnd);
  };
  return (
    <AreaView>
      {/* 图片全屏标注 */}
      <TouchableOpacity  activeOpacity={1} style={fullScreen ? styles.content_container : {display: 'none'}}
        activeOpacity={1}
        onPressIn={(evt)=> {
          onPressIn(evt);
        }}
        onPressOut={(evt)=> {
          onPressOut(evt);
        }} 
      >
        <Image
          resizeMode="contain"
          style={ fullScreen ? {flex:1,alignItems:'center',justifyContent:'center',width:null,height:null,backgroundColor:'rgba(0,0,0,0)'} : {display:'none'}}
          source={{uri: imgSrc}}
        />
        {(newEndP || []).map((item, i) => (
            <View
              key={i}
              style={[
                styles.answer_border,{
                  width: item.pageX - newStartP[i].pageX,
                  height: item.pageY - newStartP[i].pageY,
                  left: newStartP[i].pageX,
                  top: newStartP[i].pageY - px2dp(180),
                }
              ]}
            ></View>
        ))}
        {/* <View style={[
          styles.answer_border,{
            width: endP.pageX - startP.pageX,
            height: endP.pageY - startP.pageY,
            left: startP.pageX,
            top: startP.pageY - px2dp(180),
            // top: startP.pageY - (heightDe - imgHeight*scale)/2
          }
        ]}></View> */}
      </TouchableOpacity>

      {/* 全屏操作按钮 */}
      <View style={fullScreen ? {flexDirection:'row', justifyContent: 'center', marginBottom: px2dp(48)} : {display: 'none'}}>
        <TouchableOpacity
          onPress={()=> {
            setFullScreen(0);
          }}
        >
          <View style={styles.full_screen_submit}>
            <Text style={styles.submit_text}>返回</Text>
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={()=> {
            newStart = [];
            newEnd = [];
            setNewStartP([]);
            setNewEndP([]);
          }}
        >
          <View style={styles.full_screen_submit}>
            <Text style={styles.submit_text}>清除标注</Text>
          </View>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={()=> {
            setFullScreen(0);
            setAswQuestion();
            // console.log(newStartP, 'commit');
            // console.log(newEndP, 'commit end');
          }}
        >
          <View style={styles.full_screen_submit}>
            <Text style={styles.submit_text}>保存</Text>
          </View>
        </TouchableOpacity>
      </View>
      
      <ScrollView style={ fullScreen ? {display:'none'} : {display:'flex'}}>
        <TouchableOpacity
            onPress={()=> {
              setFullScreen(1);
            }}
          >
            <Image
              style={[styles.list_img,{height:imgHeight*scale}]}
              source={{uri: imgSrc}}
            />
            {(newEndP || []).map((item, i) => (
                <View
                  key={i+1234}
                  style={[
                    styles.answer_border,{
                      width: item.pageX - newStartP[i].pageX,
                      height: item.pageY - newStartP[i].pageY,
                      left: newStartP[i].pageX,
                      top: newStartP[i].pageY - px2dp(460),
                    }
                  ]}
                ></View>
            ))}
            <Text style={styles.mark_content}><Text style={styles.mark}>注：</Text>在你认为正确的位置从<Text style={styles.mark}>左上角</Text>到<Text style={styles.mark}>右下角</Text>画一条线即可</Text>
        </TouchableOpacity>
        

        <View>
          <View style={styles.content_big}>
            <Text style={styles.big_title}>{data?.epTitle}</Text>
            <Text style={styles.big_desc}>
              {data?.epDesc}
            </Text>
          </View>

          {
            answer && 
            <View style={styles.answer}>
              <Text style={styles.answer_text}>答题解析：标注{newEndP.length}个，答对0个；总共{answer.exmQstAnswers.length}个，得分{answer.aqScore}分</Text>

              <Text style={[styles.answer_text, styles.mark]}>正确标注</Text>
              <View>
                <Image
                  style={[styles.list_img,{height:imgHeight*scale}]}
                  source={{uri: imgSrc}}
                />
                {(answer.exmQstAnswers || []).map((item, i) => (
                <View key={item.eqaId} style={[
                  styles.answer_border,{
                    width: scale*(item.eqaRdx-item.eqaLux),
                    height: scale*(item.eqaRdy-item.eqaLuy),
                    left:scale * item.eqaLux,
                    top:scale * item.eqaLuy
                  }
                ]}></View>
                ))}
              </View>
            </View>
          }  
          
        </View>

        <View style={{flexDirection:'row', justifyContent: 'center', marginTop: 20}}>
          <TouchableOpacity
            onPress={()=> {
              if(paperTh>1){
                console.log('prev');
                setAnswer();
                questionList(apId, paperTh-1);
              }else{
                Toast.info('当前是第一题');
              }
            }}
          >
            <View style={[styles.full_screen_submit, paperTh>1 ? "" : styles.full_screen_submit_gray]}>
              <Text style={styles.submit_text}>上一题</Text>
            </View>
          </TouchableOpacity>

          <TouchableOpacity
            onPress={()=> {
              if(paperTh<paperTotal){
                setAnswer();
                questionList(apId, paperTh+1);
              }else{
                Toast.info('已经是最后一题了');
              }
            }}
          >
            <View style={[styles.full_screen_submit, paperTh<paperTotal ? "" : styles.full_screen_submit_gray]}>
              <Text style={styles.submit_text}>下一题</Text>
            </View>
          </TouchableOpacity>

          <TouchableOpacity
            onPress={()=> {
              navigation.push('AnswerReport', {
                epId,
                epTitle: data.epTitle,
                rightCount,
                aswQuestions,
              })
            }}
          >
            <View style={[styles.full_screen_submit, styles.submit_red]}>
              <Text style={styles.submit_text}>提交考试</Text>
            </View>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </AreaView>
  );
};

export default LabelDetail;
